<?xml version="1.0" encoding="UTF-8"?>
<html>
    <head>
        <link type="text/css" rel="stylesheet" href="./css/template.css" />
        <link type="text/css" rel="stylesheet" href="./css/SyntaxHighlighter.css" />
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
        <title>Native methods</title>
        <script language="javascript" src="./js/shInit.js" />
        <script language="javascript" src="./js/shCore.js" />
        <script language="javascript" src="./js/shBrushCpp.js" />
        <script language="javascript" src="./js/shBrushCSharp.js" />
        <script language="javascript" src="./js/shBrushCss.js" />
        <script language="javascript" src="./js/shBrushDelphi.js" />
        <script language="javascript" src="./js/shBrushJava.js" />
        <script language="javascript" src="./js/shBrushJScript.js" />
        <script language="javascript" src="./js/shBrushPhp.js" />
        <script language="javascript" src="./js/shBrushPython.js" />
        <script language="javascript" src="./js/shBrushRuby.js" />
        <script language="javascript" src="./js/shBrushSql.js" />
        <script language="javascript" src="./js/shBrushVb.js" />
        <script language="javascript" src="./js/shBrushXml.js" />
        <keywords>C functions</keywords>
        <author>Emmanuel BOUBLI</author>
    </head>
    <body>
        <div class="chapter">
            <h2>Introduction</h2>
            <p>You are probably convinced that code written in Java is better on several points than code written in languages like C or C++, even for single plateform applications.
				It is of course not a matter of portability.
				While a "100% pure Java" is nice on principle , it is unrealistic for some applications in which
				you will want to write (or use) code in another language (named native code).</p>
            <p>Three main reasons may make this choice good :</p>
            <ul>
                <li>You owe a significant amount of code, tested and debugged, in this other language.
				Code translation into Java would take long and the new code would have to be tested and debugged once again.</li>
                <li>Your application requires access to system elements or functionalities and using Java technology would be tedious or even impossible.</li>
                <li>Execution speed of your code is crucial.</li>
            </ul>
            <p>In any of these three situations, it may be smart to call native code in programs written in Java.
				Let's see how to set up native code.</p>
        </div>
        <div class="chapter">
            <h2>Calling a C function in Java language</h2>
            <div class="subChapter">
                <p>
                    Imagine that you have a C function doing a task that you particularly like, and for
					some reason, you don't want to implement it in Java again.
					For demonstration purpose, let's say that it is the very useful printf function.
					You want to call printf in your programs. Java language uses the
                    <i>native</i> keyword
                    , and you obviously have to encapsulate the
                    <i>printf</i>
                    function in a class.
					You could write something like :
                </p>
                <textarea name="code" class="java">public class Printf
					{
					public native String printf(String s);
					}</textarea>
                <p>You actually can compile this class. But when you will use it in a program, the virtual machine won't find printf. Then, it will throw
					an UnsatisfiedLinkError. So give it the required execution informations and it will be able to link the class.
					As you will soon see, the process can be made in three steps in JDK :</p>
                <ol>
                    <li>Generate a C pseudocode for a function which transmits the call from Java plateform to the actual C method.
						The pseudocode takes informations from the settings of the virtual machine stack,
						and passes it to the compiled C function.</li>
                    <li>Create a special shared library and export the pseudocode from it.</li>
                    <li>
                        Use a special method, called
                        <i>System.loadLibrary</i>
                        to tell the JRE to load the step 2 library.
                    </li>
                </ol>
                <p>We will now see how to run this steps with a few examples, starting with a special case
				of trivial printf use, and finishing with a realistic example implying the registry base for methods depending on the Java plateform.</p>
            </div>
            <div class="subChapter">
                <h3>Working with printf function</h3>
                <p>
                    Let's start with the virtually easiest way to use
                    <i>printf</i>
                    : the call of a native method which prints "Hello, Native World".
					Actually, we won't even exploit formatting functionalities of
                    <i>printf</i>
                     !
					However, it is an excellent way to verify that your C compiler works as expected
					before trying to implement more complex native methods.
                </p>
                <p>As we have already said, you have to declare the native method in a class.
					The native keyword awares the compiler that the method will be defined outside. Of course, native methods don't hold Java code, and the header is immediately followed by the ending semicolon.
					This means, as shown in the example above, that declarations of native methods are similar to those of abstract methods.</p>
                <textarea name="code" class="java">class HelloNative
					{
					public native static void greeting();
					...
					}</textarea>
                <p>In this specific example, notice that the native method is also declared as static.
					Native methods can be static or non static. They don't have arguments;
					for now, we don't want to care about passing parameters.</p>
                <p>Then write a corresponding C function.  You have to name it exactly as the Java environment expects it, which means :</p>
                <ul>
                    <li>Use the full Java method name, like HelloNative.greeting.</li>
                    <li>Replace every point by underscores, and prefix it with Java_. For example, Java_HelloNative_greeting.</li>
                    <li>If the class name contains non alphanumerical ASCII characters, like '_', '$',
					or Unicode characters '\u007F', replace them by _0xxxx, where xxxx is the hexadecimal 4 digits Unicode value of the character.</li>
                </ul>
                <p>Nobody does this manually for real; run the javah tool instead, which generates functions names.</p>
                <h4>Passing primitive types</h4>
                <p>To pass numerical values from C to Java, you have to know types correspondances. For example, the implementation of C int and long types is
					plateform dependant. On certain plateforms, integer types are 16 bits long, while on others
					they are coded on 32 bits. For this reason, the JNI (Java Native Interface) defines jint, jlong... types
					Here is a table that brings together correspondances between native types (C) and Java.</p>
                <img src="./images/01.gif" />
                <p>Let's see an example for better comprehension.
					We will define and use a native method which adds two integers and returns the sum.</p>
                <textarea name="code" class="java">class TestJNI1 {
					public native int ajouter(int a, int b);
					static {
					System.loadLibrary("mabibjni");
					}
					public static void main(String[] args) {
					TestJNI1 maclasse = new TestJNI1();
					System.out.println("2 + 3 = " + maclasse.ajouter(2,3));
					}
					}</textarea>
                <p>Nothing special in this declaration except the native modifier. The method
					signature in .h file has parameters.</p>
                <p>You just have to write the native code implementation</p>
                <textarea name="code" class="c">
                    #include
                    <jni.h>
                        #include
                        <stdio.h>#include "TestJNI2.h"
							JNIEXPORT jint JNICALL Java_TestJNI2_ajouter
							(JNIEnv *env, jobject obj, jint a, jint b)
							{
							return a + b;
							}</stdio.h>
                    </jni.h>
                </textarea>
                <p>Then you have to compile the code.
					Define the .def file.
					The following command creates a library. It will hold
					the native functions of the two Java classes previously created.</p>
                <div class="quote">
                    <span class="cmd_line_lvl">$&gt;</span>
                    <span class="cmd_line">EXPORTS Java_TestJNI2_ajouter</span>
                </div>
            </div>
            <div class="subChapter">
                <h3>Passing objects</h3>
                <p>
                    Objects are passed by reference using a
                    <i>jobject</i> type variable.
					Several other types are defined by JNI for frequently used objects :
                </p>
                <img src="./images/02.gif" />
                <p>Here is an example that concatenates two strings :</p>
                <textarea name="code" class="java">class TestJNI3 {
					public native String concat(String a, String b);
					static {
					System.loadLibrary("mabibjni");
					}
					public static void main(String[] args) {
					TestJNI3 maclasse = new TestJNI3();
					System.out.println("abc + cde = " + maclasse.concat("abc","cde"));
					}
					}</textarea>
                <p>The declaration of the native function in TestJNI3.h file is as follows :</p>
                <textarea name="code" class="c">/*
					* Class:     TestJNI3
					* Method:    concat
					* Signature: (Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String;
					*/
					JNIEXPORT jstring JNICALL Java_TestJNI3_concat
					(JNIEnv *, jobject, jstring, jstring);</textarea>
                <p>
                    To use
                    <i>jstring</i> parameters
                    in native code,
					you have to transform them with functions of the JNIEnv interface because Java Strings are not directly compatible
					with C char *.
					Some functions can transform strings coded in UTF-8 or in Unicode.
                </p>
                <p>Methods for treating UTF-8 format are :</p>
                <ul>
                    <li>
                        <i>GetStringUTFChars() :</i>
                        converts a Java string into a C string.
                    </li>
                    <li>
                        <i>NewStringUTF() :</i>
                        demands the creation of a new string.
                    </li>
                    <li>
                        <i>GetStringUTFLength() :</i>
                        returns the string size.
                    </li>
                    <li>
                        <i>ReleaseStringUTFChars() :</i>
                        demands the liberation of ressources allocated for the string as soon as it is not used.
						It prevents from memory outflows.
                    </li>
                </ul>
                <p>
                    Equivalent methods for Unicode strings are :
                    <i>GetStringChars()</i>
                    ,
                    <i>NewString()</i>
                    ,
                    <i>GetStringUTFLength()</i>
                    et
                    <i>ReleaseStringChars()</i>
                    :
                </p>
                <textarea name="code" class="c">
                    #include
                    <jni.h>
                        #include
                        <stdio.h>#include "TestJNI3.h"
							JNIEXPORT jstring JNICALL Java_TestJNI3_concat
							(JNIEnv *env, jobject obj, jstring chaine1, jstring chaine2){
							char resultat[256];
							const char *str1 = (*env)-&gt;GetStringUTFChars(env, chaine1, 0);
							const char *str2 = (*env)-&gt;GetStringUTFChars(env, chaine2, 0);
							sprintf(resultat,"%s%s", str1, str2);
							(*env)-&gt;ReleaseStringUTFChars(env, chaine1, str1);
							(*env)-&gt;ReleaseStringUTFChars(env, chaine2, str2);
							return (*env)-&gt;NewStringUTF(env, resultat);
							}</stdio.h>
                    </jni.h>
                </textarea>
                <p>
                    <font color="red">
                        <b>Caution</b>
                    </font>
                    : this code is very simplistic because it doesn't check a possible overflow of the result table.
					After compiling the different elements, running gives the expected result.
                </p>
            </div>
        </div>
        <div class="chapter">
            <h2>Errors managing</h2>
            <p>
                Native methods are a singnificant risk for Java programs security.
				The C running environment offers no protection against table overflow errors, indirection with wrong pointers, etc...
				Native methods programmers have to handle all error conditions to protect the Java plateform integrity.
				Specifically, when your native method diagnoses a problem it can't solve, it must warn the Java virtual machine.
				In such a case, you would throw an exception manually. However, there is no exception in C.
				You will have to call
                <i>Throw</i>
                or
                <i>ThrowNew</i> method instead
                to create a new Exception object.
				When exiting the native method, the JVM will throw this exception.
            </p>
            <p>
                To use the
                <i>Throw</i> function
                , call
                <i>NewObject</i>
                which creates an object inherited from
                <i>Throwable</i>
                .
				For example, here, we allocate an
                <i>EOFException</i> object
                and throw it.
            </p>
            <textarea name="code" class="c">
                jclass class EOFException=(*env)-&gt;FindClass(env,"java/io/EOFException");
				jmethodID id_EOFException=(*env)-&gt;GetMethodID(env,class_EOFException,"
                <init>","()V); /* ID du constructeur par défaut */
					jthrowable obj_exc=(*env)-&gt;NewObject(env,classEOFException,id_EOFException);
					(*env)-&gt;Throw(env,obj_exc); (*env)-&gt;NewStringUTF(env, resultat);
					}</init>
            </textarea>
            <p>
                It is more convenient to call
                <i>ThrowNew</i>
                , which builds an Exception object, from a class and an UTF string.
				These two methods don't interrupt the native method flow. The exception is thrown only when the method returns.
				Consequently, every call to
                <i>Throw</i>
                and
                <i>ThrowNew</i>
                has to be followed by a
                <i>return</i> instruction.
            </p>
        </div>
        <div class="chapter">
            <h2>Conclusion</h2>
            <p>Despite we showed that native methods can't be portable, we have however seen the interoperability of Java
				with other runnable languages.
				Thus, the programmer is offered some flexibility in using Java with a runnable language even if it is tougher to set up.</p>
        </div>
    </body>
</html>

